import React from 'react'
import {
  Form,
  Input,
  Button,
  Table,
  Divider,
  Pagination,
  Modal,
  message,
  Popconfirm
} from 'antd'
import { connect } from 'react-redux'
import _ from 'lodash'
import moment from 'moment'
import {
  productAddApi,
  productFindBypageApi,
  productConnectSmbApi,
  productUpdateApi,
  productDelApi,
  productCheckName
} from '../api/ajax'

const FormItem = Form.Item
class ProductManage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      confirmLoading: false,
      totalRecord: 0,
      tableSource: [],
      currentPage: 1,
      pageNum: 1,
      pageSize: 5,
      productName: '',
      fileName: '',
      sourceAddress: '',
      isPassLinkTest: false,
      isEdit: false,
      selectId: null,
      isFirstTest: false,
      Testing: false
    }
  }
  componentDidMount() {
    const { pageNum } = this.state
    this.loadData(pageNum)
  }

  loadData = pageNum => {
    const { pageSize, productName, fileName, sourceAddress } = this.state
    this.setState({ currentPage: pageNum, pageNum })
    productFindBypageApi({
      pageNum,
      pageSize,
      productName,
      fileName,
      sourceAddress
    }).then(v => {
      const {
        list: { totalRecord, results }
      } = v
      _.each(results, v => {
        v.key = v.id
      })
      this.setState({
        totalRecord,
        tableSource: results ? results : []
      })
    })
  }

  render() {
    const {
      getFieldDecorator,
      resetFields,
      setFieldsValue,
      validateFields,
      getFieldsValue,
      setFields
    } = this.props.form
    const {
      visible,
      confirmLoading,
      totalRecord,
      tableSource,
      pageSize,
      currentPage,
      productName,
      fileName,
      sourceAddress,
      isPassLinkTest,
      isEdit,
      selectId,
      isFirstTest,
      Testing
    } = this.state
    const rules = {
      rules: [
        {
          required: true,
          message: '字符不得为空'
        }
      ]
    }
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    let testResult = ''
    let testColor = isPassLinkTest ? 'green' : 'red'
    if (isFirstTest) {
      testResult = isPassLinkTest ? '连接成功' : '连接失败'
    } else {
      testResult = ''
    }
    return (
      <div className="home">
        <div className="home-head">
          <Form layout="inline">
            <FormItem label="产品名称">
              <Input
                value={productName}
                onChange={e => this.setState({ productName: e.target.value })}
              />
            </FormItem>
            <FormItem label="文件名称">
              <Input
                value={fileName}
                onChange={e => this.setState({ fileName: e.target.value })}
              />
            </FormItem>
            <FormItem label="源地址">
              <Input
                value={sourceAddress}
                onChange={e => this.setState({ sourceAddress: e.target.value })}
              />
            </FormItem>
            <Button
              type="primary"
              onClick={() => this.loadData(1)}
              style={{ marginRight: '10px' }}
            >
              查询
            </Button>
            <Button
              onClick={() => {
                this.setState(
                  {
                    productName: '',
                    fileName: '',
                    sourceAddress: ''
                  },
                  () => this.loadData(1)
                )
              }}
            >
              重置
            </Button>
          </Form>
        </div>
        <div className="home-body">
          <div className="home-body-head">
            <h3 className="home-body-head-title">产品列表</h3>
            <Button
              type="primary"
              onClick={() =>
                this.setState(
                  {
                    visible: true,
                    isEdit: false,
                    Testing: false
                  },
                  () => {
                    setFieldsValue({
                      productCode: moment(new Date()).format('YYYYMMDDhhmmss')
                    })
                  }
                )
              }
            >
              添加新产品
            </Button>
          </div>
          <Table
            dataSource={tableSource}
            scroll={{ x: 1200 }}
            columns={[
              {
                title: '产品编号',
                dataIndex: 'productCode'
              },
              {
                title: '产品名称',
                dataIndex: 'productName'
              },
              {
                title: '文件名',
                dataIndex: 'fileName'
              },
              {
                title: '源地址',
                dataIndex: 'sourceAddress'
              },
              {
                title: '服务器用户名',
                dataIndex: 'userName'
              },
              {
                title: '操作',
                dataIndex: 'address',
                render: (text, record) => (
                  <span>
                    <button
                      className="button-a"
                      onClick={() => {
                        const {
                          id,
                          productCode,
                          fileName,
                          password,
                          productName,
                          sourceAddress,
                          userName
                        } = record
                        this.setState({
                          visible: true,
                          confirmLoading: false,
                          isEdit: true,
                          isPassLinkTest: false,
                          selectId: id,
                          isFirstTest: false,
                          Testing: false
                        })
                        setFieldsValue({
                          productCode,
                          fileName,
                          password,
                          productName,
                          sourceAddress,
                          userName
                        })
                      }}
                    >
                      编辑
                    </button>
                    <Divider type="vertical" />
                    <Popconfirm
                      title="是否删除此条记录"
                      onConfirm={() => {
                        const { id } = record
                        productDelApi({ id }).then(v => {
                          message.success('删除成功')
                          this.loadData(1)
                        })
                      }}
                      onCancel={() => {}}
                      okText="是"
                      cancelText="否"
                    >
                      <button className="button-a">删除</button>
                    </Popconfirm>
                  </span>
                )
              }
            ]}
            pagination={false}
          />
          <div className="home-body-page">
            <Pagination
              total={totalRecord}
              pageSize={pageSize}
              current={currentPage}
              onChange={pageNum => {
                this.setState({ pageNum, currentPage: pageNum })
                this.loadData(pageNum)
              }}
              showTotal={total => `共${total}条数据`}
            />
          </div>
        </div>

        <Modal
          title={isEdit ? '编辑' : '新增'}
          visible={visible}
          onOk={() => {
            if (!isPassLinkTest) {
              message.warning('请先检测服务器连接')
              return
            }
            validateFields((errors, values) => {
              if (errors) return
              this.setState({ confirmLoading: true })
              if (isEdit) {
                values.id = selectId
                productUpdateApi(values).then(v => {
                  message.success('修改成功')
                  resetFields()
                  this.setState({
                    visible: false,
                    confirmLoading: false,
                    isFirstTest: false
                  })
                  this.loadData(1)
                })
              } else {
                productAddApi(values).then(v => {
                  message.success('新增成功')
                  resetFields()
                  this.setState({
                    visible: false,
                    confirmLoading: false,
                    isFirstTest: false
                  })
                  this.loadData(1)
                })
              }
            })
          }}
          confirmLoading={confirmLoading}
          onCancel={() => {
            resetFields()
            this.setState({
              visible: false,
              confirmLoading: false,
              isFirstTest: false
            })
          }}
        >
          <Form>
            <FormItem label="产品编号" {...formItemLayout}>
              {getFieldDecorator('productCode', rules)(<Input disabled />)}
            </FormItem>
            <FormItem label="产品名称" {...formItemLayout}>
              {getFieldDecorator('productName', rules)(
                <Input
                  autoComplete="off"
                  onBlur={v => {
                    const value = v.target.value
                    productCheckName({ name: value }).then(data => {
                      if (data) {
                        setFields({
                          productName: {
                            value: value,
                            errors: [new Error('产品名重复')]
                          }
                        })
                      }
                    })
                  }}
                />
              )}
            </FormItem>
            <FormItem label="文件名称" {...formItemLayout}>
              {getFieldDecorator('fileName')(<Input />)}
            </FormItem>
            <div>
              源地址填写示例: 192.168.0.13/test/name/ (/test/name为文件夹)
            </div>
            <FormItem label="源地址" {...formItemLayout}>
              {getFieldDecorator('sourceAddress', rules)(<Input />)}
            </FormItem>
            <FormItem label="服务器用户名" {...formItemLayout}>
              {getFieldDecorator('userName', rules)(
                <Input autoComplete="off" />
              )}
            </FormItem>
            <FormItem label="服务器密码" {...formItemLayout}>
              {getFieldDecorator('password', rules)(<Input type="password" />)}
            </FormItem>
            <div style={{ textAlign: 'right', padding: '0 40px' }}>
              <span style={{ marginRight: '30px', color: testColor }}>
                {testResult}
              </span>
              <Button
                type="primary"
                loading={Testing}
                disabled={Testing}
                onClick={() => {
                  const tcpData = getFieldsValue([
                    'sourceAddress',
                    'userName',
                    'password'
                  ])
                  this.setState({ Testing: true })
                  productConnectSmbApi(tcpData)
                    .then(isPassLinkTest => {
                      this.setState({
                        isPassLinkTest,
                        isFirstTest: true,
                        Testing: false
                      })
                    })
                    .catch(() => {
                      this.setState({ Testing: false })
                    })
                }}
              >
                连接测试
              </Button>
            </div>
          </Form>
        </Modal>
      </div>
    )
  }
}

export default connect(state => ({
  state
}))(Form.create()(ProductManage))
